# tools/request_util.py
""" 
author：Men Dong Yang
create_time：2025/5/7 16:02:43
description：
"""
import re
from datetime import datetime

import requests
from loguru import logger

date = re.sub(r'[:-]', '_', str(datetime.now())).split(' ')[0]
logger.add(f"logs/log_{date}.log", level="INFO", encoding="utf-8", enqueue=True, rotation="500MB", retention="1 week")


def execute(api_info):
    """api_info = {
        "line": {
            "host": "",
            "method": "",
            "path": ""
        },
        "headers": {
            "content-type": "",
            "authori-zation": ""
        },
        "body": {

        }
    }"""

    # 从api_info中取出method
    method = api_info['line']['method']
    # 从api_info中取出url
    url = api_info['line']['host'] + api_info['line']['path']
    # 从api_info中取出headers
    headers = api_info['headers']
    # 从api_info中取出body
    if 'body' in api_info.keys():
        body = api_info['body']
    else:
        body = None
    response = requests.request(method, url, headers=headers, json=body)
    status_code = response.status_code
    text = response.text
    if status_code == 200:
        if '"status":200' in text:
            # 发送日志
            logger.info(f'发送请求{api_info}响应结果: http状态码: {status_code} 响应body:{text}')
        else:
            logger.warning(f'发送请求{api_info}响应结果: http状态码: {status_code} 响应body:{text}')

    else:
        logger.error(f'发送请求{api_info}响应结果: http状态码: {status_code} 响应body:{text}')
    return response
